﻿namespace ExpressionsWpf
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;

    /// <summary>
    /// Adapter to ease binding to WPF.
    /// Main goal was to create an IEnumerable of child nodes.
    /// </summary>
    public class ExpressionAdapter
    {
        private readonly Expression _expression;

        private readonly string _parentPropertyName;

        public ExpressionAdapter(Expression expression, string parentPropertyName)
        {
            _expression = expression;
            _parentPropertyName = parentPropertyName;
        }

        /// <summary>
        /// Gets a string with information about the current Property-Expression pair.
        /// </summary>
        /// <value>
        /// All properties of type Expression as an IEnumerable of ExpressionAdapter.
        /// </value>
        public IEnumerable<ExpressionAdapter> Children
        {
            get
            {
                if (null == _expression)
                {
                    return null;
                }
                else
                {
                    return from child in _expression.GetType().GetProperties()
                           where child.PropertyType == typeof(Expression)
                           select new ExpressionAdapter((Expression)child.GetValue(_expression, null), child.Name);
                }
            }
        }

        public string Text
        {
            get
            {
                return _parentPropertyName + " = " + (_expression == null ? "null" : (_expression.NodeType + " : " + _expression));
            }
        }
    }
}